package org.altervista.cp.microkernel.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

public class BufferedIO {

	public static final int DEFAULT_LENGTH = 1024;

	public BufferedIO() {
		this(DEFAULT_LENGTH);
	}

	public BufferedIO(int length) {
		_length = length;
	}

	public void copy(InputStream is, OutputStream os) throws IOException {
		byte[] buffer = new byte[_length];
		for (int rb = 0; (rb = is.read(buffer)) != -1;) {
			os.write(buffer, 0, rb);
		}
		os.flush();
	}

	public void copy(Reader r, Writer w) throws IOException {
		char[] buffer = new char[_length];
		for (int rb = 0; (rb = r.read(buffer)) != -1;) {
			w.write(buffer, 0, rb);
		}
		w.flush();
	}

	public void copy(String charset, InputStream is, Writer w)
			throws IOException {
		copy(new InputStreamReader(is, charset), w);
	}

	public void copy(InputStream is, Writer w) throws IOException {
		copy(new InputStreamReader(is), w);
	}

	public void copy(String charset, Reader r, OutputStream os)
			throws IOException {
		copy(r, new OutputStreamWriter(os, charset));
	}

	public void copy(Reader r, OutputStream os) throws IOException {
		copy(r, new OutputStreamWriter(os));
	}

	private int _length;

}
